<?php
class Base {
	public static function arrayObject($array) {
		if (! is_array ( $array )) {
			return $array;
		}
		$object = new stdClass ();
		if (is_array ( $array ) && count ( $array ) > 0) {
			foreach ( $array as $name => $value ) {
				$name = strtolower ( trim ( $name ) );
				if (! empty ( $name )) {
					$object->$name = self::arrayObject ( $value );
				}
			}
			return $object;
		} else {
			return false;
		}
	}
	
	public static function objectArray($object) {
		if (is_object ( $object )) {
			$object = get_object_vars ( $object );
		}
				
		if (is_array ( $object )) {
			return array_map ( __FUNCTION__, $object );
		} else {
			return $object;
		}
	}
	
	public static function formatJsonValue(&$value) {
		if (is_bool ( $value )) {
			$value = $value ? 'TRUE' : 'FALSE';
		} else if (is_int ( $value )) {
			$value = intval ( $value );
		} else if (is_float ( $value )) {
			$value = floatval ( $value );
		} else if (defined ( $value ) && $value === NULL) {
			$value = strval ( constant ( $value ) );
		} else if (is_string ( $value )) {
			$value = '"' . addslashes ( $value ) . '"';
		}
		return $value;
	}
	
	public static function encode($data) {
		if (is_object ( $data )) {
			// 对象转换成数组
			$data = get_object_vars ( $data );
		} else if (! is_array ( $data )) {
			// 普通格式直接输出
			return $this->formatJsonValue ( $data );
		}
		// 判断是否关联数组
		if (empty ( $data ) || is_numeric ( implode ( '', array_keys ( $data ) ) )) {
			$assoc = false;
		} else {
			$assoc = true;
		}
		// 组装 Json字符串
		$json = $assoc ? '{' : '[';
		foreach ( $data as $key => $val ) {
			if (! is_NULL ( $val )) {
				if ($assoc) {
					$json .= "\"$key\":" . self::_encode ( $val ) . ",";
				} else {
					$json .= self::_encode ( $val ) . ",";
				}
			}
		}
		if (strlen ( $json ) > 1) { // 加上判断 防止空数组
			$json = substr ( $json, 0, - 1 );
		}
		$json .= $assoc ? '}' : ']';
		return $json;
	}
	
	/**
	 *
	 * @access public
	 * @param string $json
	 *        	json数据
	 * @param string $assoc
	 *        	当该参数为 TRUE 时，将返回 array 而非 object
	 * @return string
	 */
	public static function decode($json, $assoc = FALSE) {
		// 目前不支持二维数组或对象
		$begin = substr ( $json, 0, 1 );
		if (! in_array ( $begin, array (
				'{',
				'['
		) ))
			return $json; // 不是对象或者数组直接返回
		$parse = substr ( $json, 1, - 1 );
		$data = explode ( ',', $parse );
		if ($flag = $begin == '{') {
			// 转换成PHP对象
			$result = new stdClass ();
			foreach ( $data as $val ) {
				$item = explode ( ':', $val );
				$key = substr ( $item [0], 1, - 1 );
				$result->$key = self::_decode ( $item [1], $assoc );
			}
			if ($assoc)
				$result = get_object_vars ( $result );
		} else {
			// 转换成PHP数组
			$result = array ();
			foreach ( $data as $val )
				$result [] = self::_decode ( $val, $assoc );
		}
		return $result;
	}
}
?>